//https://codeantenna.com/a/vL7AgQieGw（table前后端数据接口）
//


const Koa    = require('koa');
const Router = require('koa-router');
const fs     = require('fs');
const path   = require('path');
const bodyParser = require('koa-bodyparser');
const app    = new Koa();

const {findData, insertData} = require('./tools/sql_exec');

const static = require('koa-static');
const static_path = './layui';
app.use(static(
    path.join(__dirname, static_path)
))

app.use(bodyParser());

async function render(page){
    return new Promise((resolve, reject) => {
        let view = './layui/' + page;
        fs.readFile(view, 'binary', (err, data) => {
            if(err){
                reject(err);
            }else{
                resolve(data);
            }
        })
    })
}

async function insertDataExec(data){
    let r = await insertData(data);
    return r;
}

//子路由1
let home = new Router();
home.get('/', async(ctx) => {
    console.log('./');
    let html = await render('index.html');
    ctx.body = html;
}).get('index.html', async(ctx) => {
    console.log('index.html');
    ctx.body = await render('index.html');
})

//子路由2
let view = new Router();
view.get('404.html', async(ctx) => {
    console.log('404.html');
    ctx.body = await render('404.html');
}).get('nav.html', async(ctx) => {
    console.log('/nav.html')
    ctx.body = await render('nav.html');
}).get('table/user/', async(ctx) => {
    var data_list = await findData();
    console.log('table/user');
    console.log(ctx.request.query);
    console.log(data_list);
    var return_data = {
        code:0,
        msg: "成功",
        count: data_list.length,
        data: data_list
    };

    ctx.body = return_data;
})

view.post('userPost', async(ctx) => {
    console.log('/userPost')
    //当POST请求时，使用bodyParser中间件解析POST表单的数据
    var post_data = ctx.request.body;
    console.log(post_data);

    let id_judge = 0;
    await insertDataExec(post_data)
        .then(r => {
            console.log("r: " + r);
        })
        .catch(err => {
            id_judge = 19;
            console.log("err");
        })

    ctx.body = {
        id_judge: id_judge
    };

})

//console.log(render('index.html'));

//装载所有子路由
let router = new Router();
//此处路由路径和view.get、home.get结合，对应html页面中链接路径
//路由路径非绝对路径，注意区分
router.use('/', home.routes(), home.allowedMethods());
router.use('/', view.routes(), view.allowedMethods());

//加载路由中间件
app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
    console.log('starting...');
})
